# 创建路由对象
from datetime import datetime

from fastapi import APIRouter, HTTPException
from pydantic import BaseModel

from controller.system.login_api import resp, resp_data, resp_page
from dao.task.task_dao import TaskInfo
from init.mysql import get_session

task_api = APIRouter()


class TaskVO(BaseModel):
    id: int | None = 0
    name: str
    url: str
    url2: str
    period: int | None = 0
    request_frequency: int | None = 0
    comment: str
    format: str
    update_time: str | None = None
    start_time: datetime | None = None
    end_time: datetime | None = None
    count: int | None = 0


# CRUD服务接口
@task_api.post("/task")
async def create_task(task: TaskVO):
    db = get_session()
    print(task.dict)
    db_task = TaskInfo(**task.dict())
    db.add(db_task)
    db.commit()
    db.close()
    return resp()


@task_api.get("/task/{task_id}")
async def read_task(task_id: str):
    db = get_session()
    db_task = db.query(TaskInfo).filter(TaskInfo.id == task_id).first()
    db.commit()
    db.close()
    if not db_task:
        raise HTTPException(status_code=404, detail="Task not found")
    return db_task


@task_api.put("/task/{task_id}")
async def update_task(task_id: str, task: TaskVO):
    db = get_session()
    db_task = db.query(TaskInfo).filter(TaskInfo.id == task_id).first()
    if not db_task:
        raise HTTPException(status_code=404, detail="Task not found")
    for key, value in task.dict().items():
        if value is not None:
            setattr(db_task, key, value)
    db.commit()
    db.close()
    return {"id": db_task.id}


@task_api.delete("/task/{task_id}")
async def delete_task(task_id: str):
    db = get_session()
    db_task = db.query(TaskInfo).filter(TaskInfo.id == task_id).first()
    if db_task:
        db.delete(db_task)
    db.commit()
    db.close()
    return resp()


@task_api.get("/task")
async def read_task(name: str | None = None):
    print(name)
    db = get_session()
    tasks = db.query(TaskInfo).all()
    data = [t.serialize() for t in tasks]
    db.commit()
    db.close()
    return resp_page(data, len(tasks))
